//
//  QLSellTicketViewController.m
//  QLThread
//
//  Created by Shrek on 15/5/26.
//  Copyright (c) 2015年 Personal. All rights reserved.
//

#import "QLSellTicketViewController.h"

@interface QLSellTicketViewController ()
{
    NSInteger _countTicket;
    NSThread *_thread0;
    NSThread *_thread1;
    NSThread *_thread2;
}

@end

@implementation QLSellTicketViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _countTicket = 100;
    
    _thread0 = [[NSThread alloc] initWithTarget:self selector:@selector(sell) object:nil];
    _thread0.name = @"Seller A";
    _thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(sell) object:nil];
    _thread1.name = @"Seller B";
    _thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(sell) object:nil];
    _thread2.name = @"Seller C";
}

- (IBAction)sellAction:(UIButton *)sender {
    [_thread0 start];
    [_thread1 start];
    [_thread2 start];
}

- (void)sell {
    while (1) {
        @synchronized(self) {
            NSInteger countTicketLeft = _countTicket;
            if (countTicketLeft > 0) {
                _countTicket -= 1;
                NSLog(@"%@%@", [NSThread currentThread].name, @(_countTicket));
            } else {
                [NSThread exit];
                break;
            }
        }
    }
}

@end
